package com.dao;

import exception.TransferException;
import org.apache.ibatis.session.SqlSession;
import pojo.Account;
import utils.MyUtil;

import java.math.BigDecimal;

public class AccountDaoImpl implements AccountDao {

    @Override
    public int updateAccount(BigDecimal balance, String actno) {
        SqlSession session = MyUtil.getMybatisSqlSession();
        int update = 0;
        try {
            Account account = new Account();
            account.setBalance(balance);
            account.setActno(actno);
            update = session.update("dao.AccountDao.updateAccount", account);
            session.commit();
        }catch (Exception e){
            session.rollback();
            e.printStackTrace();
        }finally {
            MyUtil.closeSession(session);
        }
        System.out.println("update = " + update);
        return update;
    }

    @Override
    public int transfer(Account fromActNo, Account toActNo) throws TransferException {
        SqlSession session = MyUtil.getMybatisSqlSession();
        int update = 0;
        try {
            update = session.update("dao.AccountDao.updateAccount", fromActNo);
            //int a = 1/0;
            update += session.update("dao.AccountDao.updateAccount", toActNo);
            session.commit();
        }catch (Exception e){
            session.rollback();
            throw new TransferException("转账失败："+e);
        }finally {
            MyUtil.closeSession(session);
        }
        return update;
    }

    @Override
    public Account selectAccountByActNo(String actno) {
        SqlSession session = MyUtil.getMybatisSqlSession();
        return session.selectOne("dao.AccountDao.selectAccountByActNo", actno);
    }
}
